import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import User from '../views/User.vue'
import Login from '../views/Login.vue'
// 导入vuex数据
import store from'../store/index';
Vue.use(VueRouter)

const routes = [
  {
    path: '',
    name: 'Home',
    component: Home,
    //路由元信息
    meta: {
      isLogin: false
    },
  },
  {
    path: '/user',
    name: 'User',
    component: User,
    meta: {
      isLogin: true
    }
  },
  {
    path: '/login',
    name: 'Login',
    component: Login,
    isLogin: false
  }

]

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
})

//路由拦截
router.beforeEach((to, from, next) => {
  // console.log('to', to);
  //判断是否需要登录界面
  if(to.matched.some(ele=>ele.meta.isLogin)){
    // 二次判断是否用户已经登录
    let token = store.state.userInfo.token;
    if(token){
      next();
    }else{
      next('/login');
    }
  }else{//不需要登录
    next();
  }
})

export default router
